<!-- 订单列表 -->
<template>
  <SearchTable :query="data.query" :list="data.list" :total="data.total" :showExport="false" @changeSize="changeSize"
    @changePage="changePage" @search="getSearchList" @reset="onHideDetails(true)" @changeTh="data.dialogVisible = true">
    <!-- @download="getExport" -->
    <template #form>
      <Operator ref="OperatorRef" @query="queryItem" />
      <el-form-item label="订单类型：">
        <el-select v-model="data.query.action_type" placeholder="请选择">
          <el-option label="全部" :value="-1" />
          <el-option v-for="item in ACTIONTYPE" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态：">
        <el-select v-model="data.query.state" placeholder="请选择">
          <el-option label="全部" :value="-1" />
          <el-option v-for="item in ORDERSTATE" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单原因：">
        <el-select v-model="data.query.reason" placeholder="请选择">
          <el-option label="全部" value="" />
          <el-option v-for="item in OrderMessage" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单处理：">
        <el-select v-model="data.query.action_state" placeholder="请选择">
          <el-option label="全部" :value="-1" />
          <el-option v-for="item in data.actionList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-select class="selectWidth120" v-model="data.query.search_type" placeholder="请选择">
          <el-option v-for="item in data.conditionList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input class="width200" v-model="data.query.search_value" placeholder="请输入" clearable />
      </el-form-item>
      <GameItem ref="GameItemRef" @query="queryGame" />
      <el-form-item label="订单编号：">
        <el-input v-model="data.query.order_id" placeholder="请输入" onKeyUp="value=value.replace(/[\W]/g,'')" />
      </el-form-item>
      <el-form-item label="牌局编号：">
        <el-input type="text" v-model="data.query.round_id_str" placeholder="请输入" onKeyUp="value=value.replace(/[\W]/g,'')" />
      </el-form-item>
      <el-form-item label="日期时间：">
        <el-date-picker v-model="data.query.date" type="datetimerange" range-separator="-" start-placeholder="请选择开始时间" end-placeholder="请选择结束时间" 
          value-format="YYYY-MM-DD HH:mm:ss" :clearable="false" :default-time="data.defaultTime" :disabled-date="indexStore.disabledDateTime"/>
      </el-form-item>
    </template>
    <template #button>
      <el-button type="warning" @click="getCheckOrder">有下注无验证牌局</el-button>
      <div class="statistic flexBetween">
        <div class="flex">
          <!-- <p>总下注金额： <span>{{ data.totalForm.sum_bet }}</span></p>
          <p>总赢：<span class="colorGre">{{ data.totalForm.sum_win }}</span></p>
          <p>总输：<span class="colorRed">{{ data.totalForm.sum_lose }}</span></p>
          <p>下注次数：<span>{{ data.totalForm.bet_times }}</span></p>
          <p>余额变动：<span :class="colorClass(data.totalForm.sum_amount)">{{ data.totalForm.sum_amount }}</span></p> -->
        </div>
      </div>
    </template>
    <template #table>
      <template v-for="(item, index) in data.fields" :key="index">
        <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width"
          show-overflow-tooltip>
          <template #header>
            <el-tooltip v-if="item.tips" effect="dark" placement="top">
              <template #content>
                <div v-if="item.prop != 'action_type'">{{ item.tips }}</div>
                <div v-else>
                  下注：玩家下注行为；<br />取消下注：玩家成功下注后，取消下注行为；<br />返奖：游戏结算给玩家返奖行为；<br />验证：用户余额经由我方与商户的接口进行验证比对行为；<br />宝箱返奖：LuckWin游戏的玩法结算；
                </div>
              </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            {{ item.label }}
          </template>
          <template v-if="item.prop == 'created_time_stamp'" #default="scope">
            {{ setTimestampTime(scope.row.created_time_stamp) }}
          </template>
          <template v-if="item.prop == 'state'" #default="scope">
            <el-tag :type="scope.row.msgId == 10001 ? 'warning' : scope.row.state == 1 ? 'success' : 'danger'">{{
              scope.row.msgId == 10001 ? '警告' : selectToLabel(ORDERSTATE, scope.row.state) }}</el-tag>
          </template>
          <template v-if="item.prop == 'msgId'" #default="scope">
            <span v-show="scope.row.state == 1">订单成功</span>
            <span v-show="scope.row.state != 1 && selectToLabel(OrderMessage, scope.row.msgId)">{{
              selectToLabel(OrderMessage, scope.row.msgId) }}</span>
          </template>
          <template v-if="item.prop == 'agent_id'" #default="scope">
            {{ selectToLabel(indexStore.agentArray, scope.row.agent_id) }}
          </template>
          <template v-if="item.prop == 'account'" #default="scope">
            <span class="item_details" @click="data.isUserDetails = true, data.checkedItem = scope.row">
              {{ scope.row.account }}
            </span>
          </template>
          <template v-if="item.prop == 'game_id'" #default="scope">
            <GameHeaderInfo class="marginB5" :game_id="scope.row.game_id" />
          </template>
          <template v-if="item.prop == 'game_type'" #default="scope">
            <el-tag type="primary">{{ selectToLabel(GAMETYPE, scope.row.game_type) }}</el-tag>
          </template>
          <template v-if="item.prop == 'before'" #default="scope">
            <span :class="colorClass(scope.row.before)">{{ scope.row.before }}</span>
          </template>
          <template v-if="item.prop == 'after'" #default="scope">
            <span :class="colorClass(scope.row.after)">{{ scope.row.after }}</span>
          </template>
          <template v-if="item.prop == 'ip'" #default="scope">
            {{ scope.row.ip }}
            <span v-if="scope.row.ip_country">({{ scope.row.ip_country }})</span>
          </template>
          <template v-if="item.prop == 'action_type'" #default="scope">
            <el-tag :type="scope.row.action_type == 1 ? 'success' : 'danger'">{{ selectToLabel(ACTIONTYPE,
              scope.row.action_type)
              }}</el-tag>
          </template>
          <template v-if="item.prop == 'wallet_type'" #default="scope">
            <el-tag type="primary">{{ selectToLabel(APITYPEShow, scope.row.wallet_type) }}</el-tag>
          </template>
          <template v-if="item.prop == 'action_state'" #default="scope">
            <el-tag :type="scope.row.action_state == 1 ? 'primary' : 'warning'">{{ selectToLabel(data.actionList,
              scope.row.action_state) }}</el-tag>
          </template>
          <template v-if="item.prop == 'manager_id'" #default="scope">
            {{ scope.row.manager_name }}
          </template>
          <template v-if="item.prop == 'action_time'" #default="scope">
            <span v-if="scope.row.action_time">{{ setTimestampTime(scope.row.action_time) }}</span>
            <span v-else> - </span>
          </template>
        </el-table-column>
      </template>
      <el-table-column fixed="right" label="操作" width="180">
        <template #header>
          <el-tooltip effect="dark" content="查看此条记录详情日志描述" placement="top">
            <el-icon class="ques-tips">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
          详情
        </template>
        <template #default="scope">
          <el-button type="success" :disabled="data.isNotRoundDetails || (scope.row.err_desc ? false : true)" v-permiss="'/system/destroyManager'"
            size="small" @click="checkDetails(scope.row)">
            详情
          </el-button>
          <el-button type="warning" v-if="!indexStore.is_general_agent"
            :disabled="data.isNotRoundDetails || (scope.row.action_state == 1 ? true : false)" v-permiss="'/system/destroyManager'" size="small"
            @click="checkAction(scope.row)">
            处理订单
          </el-button>
        </template>
      </el-table-column>
    </template>
  </SearchTable>

  <!-- 变更表头弹框 -->
  <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
    @resetData="resetData"/>
  <!-- 订单详情 -->
  <OrderDetails :show="data.isShowDetails" :checkedItem="data.checkedItem" @onHideDetails="onHideDetails" />
  <!-- 玩家信息详情 -->
  <UserDetails :show="data.isUserDetails" @onHideDetails="onHideDetails" :checkedItem="data.checkedItem" />

  <!-- 处理订单 -->
  <el-dialog v-model="data.isActionDetails" title="处理订单" :close-on-click-modal="false" :close-on-press-escape="false"
    top="30vh" @close="onHideDetails">
    <p class="box-title">
      订单编号：【<span class="mustPass">{{ data.checkedItem.order_id }}</span>】
    </p>
    <form-item title="备注" :pass="true" value="reason">
      <el-input class="margin10 width320" type="textarea" row="4" v-model="data.orderRemark" placeholder="请输入备注"
        clearable />
    </form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button :disabled="!data.orderRemark" icon="CircleCheck" type="primary" size="small" v-loading="indexStore.moduleLoading"
          @click="actionOrderState">确 认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUpdated } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Operator, { type QueryType } from '@/components/FormItem/Operator.vue'
import GameItem, { type GameType } from '@/components/FormItem/GameItem.vue'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import OrderDetails from '@/views/player/components/order-details.vue'
import UserDetails from '@/views/player/components/user-details.vue'
import GameHeaderInfo from '@/components/FormItem/GameHeaderInfo.vue'
import { GAMETYPE, ACTIONTYPE, ORDERSTATE, OrderMessage, APITYPEShow } from '@/config/eunm'
import { selectToLabel, colorClass } from '@/utils/index'
import { BigWan } from '@/utils/math'
import { getDateDayHms, setTimeValueHms, setTimestampTime } from '@/utils/time'
import { getOrder, getNotValid, actionOrder } from '@/api/player'

import { useStore } from '@/stores/index'
const indexStore = useStore()

const data = reactive({
  query: {
    page: 1,
    size: 50,
    search_type: 3,
    search_value: '',
    reason: '',
    agent_id: -1,
    operated_id: -1,
    game_id: -1,
    platform: -1,
    account3d_id: '',
    state: -1,
    action_type: -1,
    order_id: '',
    round_id_str: '',
    action_state: -1,
    date: getDateDayHms(0),
  },
  list: [],
  total: 0,
  defaultTime:[
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 59),
  ],
  conditionList: [
    { label: '平台ID', value: 1 },
    { label: '平台昵称', value: 3 }
  ],
  statusList: [
    { label: '成功', value: 1 },
    { label: '异常', value: 2 },
    { label: '警告', value: 3 },
  ],
  actionList: [
    { label: '待处理', value: 0 },
    { label: '已处理', value: 1 },
  ],
  fields: [
    { label: '创建时间', prop: 'created_time_stamp', width: '200', visible: true, tips: '此条订单记录的生成时间筛选框的日期时间筛序即此时间' },
    { label: '订单编号', prop: 'order_id', width: '240', visible: true, tips: '此条记录的编号，唯一' },
    { label: '牌局编号', prop: 'round_id_str', width: '200', visible: true, tips: '此条游戏记录的编号，唯一，对应客户端的展示用于比对查找' },
    { label: '状态', prop: 'state', width: '110', visible: true, tips: '此条订单经由我方平台与商户接口验证成功返回的状态，警告为用户余额不足，异常情况多种务必查看详情' },
    { label: '原因', prop: 'msgId', width: '120', visible: true, tips: '此条订单记录的验证返回说明与“状态”匹配说明' },
    { label: '平台昵称', prop: 'account', width: '150', visible: true, tips: '玩家名称' },
    { label: '商户昵称', prop: 'agent_id', width: '150', visible: true, tips: '此玩家所属商户' },
    { label: '地区', prop: 'area', width: '90', visible: true, tips: '此玩家所属商户的地区' },
    { label: '游戏', prop: 'game_id', width: '180', visible: true, tips: '此条记录的产生来源，游戏的名称说明' },
    { label: '游戏类型', prop: 'game_type', width: '120', visible: true, tips: '此游戏的类型，区分为百人、MiniGame、老虎机' },
    { label: '变更前', prop: 'before', width: '180', visible: true, sortable: true, tips: '此局游戏玩家金额变动前的持有' },
    { label: '变更后', prop: 'after', width: '180', visible: true, sortable: true, tips: '此局游戏玩家金额变动后的持有' },
    { label: '下注金额', prop: 'bet', width: '120', visible: true, sortable: true, tips: '此局游戏玩家的下注额度' },
    { label: '变动金额', prop: 'amount', width: '120', visible: true, sortable: true, tips: '此局游戏玩家的输赢情况，正为玩家盈利，负为玩家亏损' },
    { label: 'IP', prop: 'ip', width: '180', visible: true, tips: '此局游戏时玩家的IP地址' },
    { label: '订单类型', prop: 'action_type', width: '120', visible: true, tips: '下注：玩家下注行为；取消下注：玩家成功下注后，取消下注行为；返奖：游戏结算给玩家返奖行为；验证：用户余额经由我方与商户的接口进行验证比对行为；宝箱返奖：LuckWin游戏的玩法结算' },
    { label: '钱包类型', prop: 'wallet_type', width: '120', visible: true, tips: '商户钱包类型' },
    // { label: '第三方GID', prop: 'third_gid', width: '180', visible: true, tips: '第三方的gid' },
    { label: '处理', prop: 'action_state', width: '120', visible: !indexStore.is_general_agent },
    { label: '备注', prop: 'remark', width: '150', visible: !indexStore.is_general_agent },
    { label: '操作人', prop: 'manager_id', width: '240', visible: !indexStore.is_general_agent },
    { label: '操作时间', prop: 'action_time', width: '150', visible: !indexStore.is_general_agent },
  ],
  dialogVisible: false,
  isShowDetails: false,
  isUserDetails: false,
  isActionDetails: false,
  isNotRoundDetails: false,
  checkedItem: {} as any,
  orderRemark: '',
  totalForm: {
    bet_times: 0,
    sum_amount: 0,
    sum_bet: 0,
    sum_lose: 0,
    sum_win: 0,
  }
})

// 商户类别 + 商户
const queryItem = (item: QueryType) => {
  data.query.agent_id = item.agent_id
  data.query.operated_id = item.operated_id
}
// 游戏品牌 + 游戏
const queryGame = (item: GameType) => {
  data.query.platform = item.platform
  data.query.game_id = item.game_id
}

onMounted(async () => {
  data.query = indexStore.setQueryCache(data.query,'get')
  OperatorRef.value.setBackQuery(data.query)
  GameItemRef.value.setBackQuery(data.query)
  getSearchList()
})
onUpdated(() => {
  indexStore.setQueryCache(data.query,'set')
})

const getSearchList = async () => {
  indexStore.setPageLoading(true)
  data.isNotRoundDetails = false
  data.query = setTimeValueHms(data.query)
  let res = await getOrder(data.query)
  res.data?.list?.result?.forEach((item: any) => {
    item.before = BigWan(item.before)
    item.bet = BigWan(item.bet)
    item.amount = BigWan(item.amount)
    item.after = BigWan(item.after)
    item.msgId = 0
    item.uid = item.user_id
    // 第三方ID 有third_gid就展示third_gid没有就正常展示
    if(item.third_gid){
      item.round_id_str = item.third_gid
    }
    try {
      if (item.wallet_type == 1) {
        if (JSON.parse(item.err_desc) && JSON.parse(item.err_desc).rsp && JSON.parse(item.err_desc).rsp?.includes('code')) {
          if (item.wallet_type == 1 && JSON.parse(item.err_desc).rsp) {
            item.msgId = JSON.parse(JSON.parse(item.err_desc).rsp).code ? JSON.parse(JSON.parse(item.err_desc).rsp).code : 0
          }
        }
      } else {
        if (JSON.parse(item.err_desc) && JSON.parse(item.err_desc).rsp && JSON.parse(item.err_desc)?.rsp?.status) {
          if (JSON.parse(item.err_desc).rsp && JSON.parse(item.err_desc)?.rsp?.status == 1) {
            item.msgId = 1
          } else if (JSON.parse(item.err_desc)?.rsp?.status == 50007) {
            item.msgId = 10001
          } else {
            item.msgId = 0
          }
        }
      }
    } catch (error) {
      item.msgId = 0
    }
  })
  data.list = res.data.list.result
  data.total = res.data.total
}
const getCheckOrder = async () =>{
  data.query = setTimeValueHms(data.query)
  let res = await getNotValid(data.query)
  res.data?.list?.forEach((item: any) => {
    item.before = BigWan(item.before)
    item.bet = BigWan(item.bet)
    item.amount = BigWan(item.amount)
    item.after = BigWan(item.after)
    item.msgId = 0
    try {
      if (item.wallet_type == 1) {
        if (JSON.parse(item.err_desc) && JSON.parse(item.err_desc).rsp && JSON.parse(item.err_desc).rsp?.includes('code')) {
          if (item.wallet_type == 1 && JSON.parse(item.err_desc).rsp) {
            item.msgId = JSON.parse(JSON.parse(item.err_desc).rsp).code ? JSON.parse(JSON.parse(item.err_desc).rsp).code : 0
          }
        }
      } else {
        if (JSON.parse(item.err_desc) && JSON.parse(item.err_desc).rsp && JSON.parse(item.err_desc)?.rsp?.status) {
          if (JSON.parse(item.err_desc).rsp && JSON.parse(item.err_desc)?.rsp?.status == 1) {
            item.msgId = 1
          } else if (JSON.parse(item.err_desc)?.rsp?.status == 50007) {
            item.msgId = 10001
          } else {
            item.msgId = 0
          }
        }
      }
    } catch (error) {
      item.msgId = 0
    }
  })
  data.isNotRoundDetails = true
  data.list = res.data.list
}
// 详情
const checkDetails = async (row: any) => {
  data.isShowDetails = true
  data.checkedItem = row
}

// 处理订单
const checkAction = (row: any) => {
  data.isActionDetails = true
  Object.assign(data.checkedItem, row)
}
const actionOrderState = () => {
  let row = data.checkedItem as any;
  ElMessageBox.confirm(`是否处理商户【${row.agent_id}】${selectToLabel(indexStore.agentArray, row.agent_id)}的【${row.order_id}】订单？`, '处理',
  {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    indexStore.setModuleLoading(true)
    await actionOrder({
      id: row.id,
      status: 1,
      remark: data.orderRemark,
      region:row.region
    })
    ElMessage.success('结算成功')
    onHideDetails(true)
  }).catch(() => { })
}
// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
}

const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}

// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const OperatorRef = ref<any>()
const GameItemRef = ref<any>()
const onHideDetails = (show: boolean) => {
  data.dialogVisible = false
  data.isShowDetails = false
  data.isUserDetails = false
  data.isActionDetails = false
  data.isNotRoundDetails = false
  data.checkedItem = {} as any
  if (show) {
    data.query = {
      page: 1,
      size: 50,
      search_type: 3,
      reason: '',
      search_value: '',
      agent_id: -1,
      operated_id: -1,
      platform: -1,
      game_id: -1,
      account3d_id: '',
      action_type: -1,
      action_state: -1,
      state: -1,
      order_id: '',
      round_id_str: '',
      date: getDateDayHms(0),
    }
    getSearchList()
    OperatorRef.value.onHideDetails()
    GameItemRef.value.onHideDetails(-1)
  }
}
</script>

<style scoped lang="scss"></style>
